/**
 * JungoMobileWeb
 * IndexController.java
 * 
 * Copyright 2013 Teachizen
 * Written by cloudstick
 *	2013. 7. 26. first written.
 *
 * note:
 */
package com.jungo.web.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jungo.web.bean.Product;
import com.jungo.web.dao.ProductDao;
import com.jungo.web.util.JsonUtil;

/**
 * @author cloudstick
 *
 */
@Controller
public class IndexController {
	
	@Autowired
	private ProductDao productDao;
	
	@Autowired
	private MessageSourceAccessor messageSourceAccessor;
	
	@RequestMapping({"/", "/index.do"})
	public String index(ModelMap map) {
		
		List<Product> products = productDao.getProductByCount(null);
		if ( products == null || products.isEmpty() ) {
			map.addAttribute("slideCode", "default");
			return "index";
		} 
		
		for( Product product : products ) {
			product.setImage_path(getImageVirtualPath(product.getImage_path()));
		}
		
		map.addAttribute("slideCode", "product");
		map.addAttribute("products", products);
		
		return "index";
	}
	
	private String getImageBigVirtualPath(String imagePath) {
		return getMessage("RESOURCE.IMAGE.PATH.BIG.VIRTUAL.BASE") + imagePath;
	}
	
	private String getImageVirtualPath(String imagePath) {
		return getMessage("RESOURCE.IMAGE.PATH.VIRTUAL.BASE") + imagePath;
	}
	
	private String getMessage(String code) {
		return messageSourceAccessor.getMessage(code);
	}
	
	@RequestMapping(value="/indexProduct.do", method=RequestMethod.POST)
	@ResponseBody
	public String indexProduct(@RequestParam("category") String category) {
		List<Product> products = productDao.getProductByCount(category);
		if ( products == null || products.isEmpty() ) {
			return "";
		} 
		
		for( Product product : products ) {
			product.setImage_path(getImageVirtualPath(product.getImage_path()));
		}
		
		String jsonData = "";
		jsonData = encodeURIComponent(JsonUtil.getJsonString(products), "UTF-8");
		
		return jsonData;
	}
	
	public static String encodeURIComponent(String s, String encoding) {
		String result = null;

		try {
			result = URLEncoder.encode(s, encoding)
                 .replaceAll("\\+", "%20")
                 .replaceAll("\\%21", "!")
                 .replaceAll("\\%27", "'")
                 .replaceAll("\\%28", "(")
                 .replaceAll("\\%29", ")")
                 .replaceAll("\\%7E", "~");
		} catch (UnsupportedEncodingException e) {
			result = s;
		}

		return result;
	}  
}
